package com.briup.shopadmin.service.impl;

import com.briup.shopadmin.common.GlobalException;
import com.briup.shopadmin.common.bean.Banner;
import com.briup.shopadmin.dao.IBannerDao;
import com.briup.shopadmin.service.IBannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

@Service
public class BannerServiceImpl implements IBannerService {
    @Autowired
    IBannerDao bannerDao;
    @Override
    public Page<Banner> findAll(String title, String active, Integer pageSize, Integer pageNum) {
        if (pageSize<1||pageNum<1){
            throw new GlobalException(52001,"分页参数异常");
        }else {
            PageRequest request = PageRequest.of(pageNum - 1, pageSize);
            if (active.equals("")){
                Page<Banner> page = bannerDao.findByTitleContainingOrderByActiveDesc(title, request);
                return page;
            }else {
                Page<Banner> page = bannerDao.findByTitleContainingAndActiveOrderByActiveDesc(title, active.equals("true") ? true : false, request);
                return page;
            }
        }

    }

    @Override
    public void save(Banner banner) {
        bannerDao.save(banner);
    }

    @Override
    public void updateActive(Long id) {
//        先去查 当前轮播的状态  然后取反再保存
        Banner banner = bannerDao.findById(id).get();
//        新的轮播状态是原来的轮播状态取反
        banner.setActive(!banner.isActive());
        bannerDao.save(banner);
    }
}
